package cn.js.sangu.unitStore.common.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * https配置，将http请求全部转发到https，访问http端口也指向https
 *
 */
@Configuration
public class HttpsConfig {

    // @Value("${custom.http-port:8080}")
    // private Integer httpPort;
    //
    // @Value("${server.port:8888}")
    // private Integer port;

    @Autowired
    MyAppConfig myAppConfig;

    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        // 将http请求转换为https请求
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                // 默认为NONE
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                // 所有的东西都https
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

    /**
     * 强制将所有的http请求转发到https
     *
     * @return httpConnector
     */
    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        // connector监听的http端口号，添加空值检查
        Integer httpPort = (myAppConfig != null && myAppConfig.getHttpPort() != null) ? myAppConfig.getHttpPort()
                : 8080;
        connector.setPort(httpPort);
        connector.setSecure(false);
        // 监听到http的端口号后转向到的https的端口号，添加空值检查
        Integer httpsPort = (myAppConfig != null && myAppConfig.getHttpsPort() != null) ? myAppConfig.getHttpsPort()
                : 8081;
        connector.setRedirectPort(httpsPort);
        return connector;
    }
}
